import os
import shelve
import sys

from PySide6.QtCore import QThread, Slot
from PySide6.QtGui import QColor, QTextCursor
from PySide6.QtWidgets import QApplication, QFileDialog, QMainWindow, QWidget

sys.path.append(os.path.dirname(__file__))

from main_ui import Ui_Form
from ncm_core import TransformObject, TransformResult


class MainWindow(QWidget):
    def __init__(self, parent: QWidget | None = None) -> None:
        super().__init__(parent)
        self.ui = Ui_Form()
        self.ui.setupUi(self)

        self.obj = TransformObject()
        self.obj.startSig.connect(self.on_start)
        self.obj.resultSig.connect(self.on_result)
        self.obj.finishSig.connect(self.on_finish)

        self.qthread = QThread(parent)

        self.qthread.started.connect(self.obj.transform)
        self.obj.moveToThread(self.qthread)

        os.makedirs("cache", exist_ok=True)
        with shelve.open("cache/cache.dump", writeback=True) as db:
            self.ui.ncmFilePath.setText(db.get("ncm_file_path"))
            self.ui.outFilePath.setText(db.get("out_file_path"))
            self.ui.maxWorkers.setValue(
                db.get("max_workers") or self.ui.maxWorkers.value()
            )

    @Slot()
    def on_btnNcmFile_clicked(self):
        self.ncm_file_path = QFileDialog.getExistingDirectory(QMainWindow(), "选择文件夹")
        self.ui.ncmFilePath.setText(self.ncm_file_path)

    @Slot()
    def on_btnOutFile_clicked(self):
        self.out_file_path = QFileDialog.getExistingDirectory(QMainWindow(), "选择文件夹")
        self.ui.outFilePath.setText(self.out_file_path)

    def window_lock(self, arg: bool):
        self.ui.btnNcmFile.setDisabled(arg)
        self.ui.btnOutFile.setDisabled(arg)
        self.ui.btnTransform.setDisabled(arg)
        self.ui.maxWorkers.setDisabled(arg)
        self.ui.ncmFilePath.setDisabled(arg)
        self.ui.outFilePath.setDisabled(arg)

    def on_start(self, text):
        self.window_lock(True)
        self.output(text)

    def on_result(self, result: TransformResult):
        self.output(result.msg, result.color)

    def on_finish(self, text, color):
        self.output(text, color)
        self.window_lock(False)
        self.qthread.quit()

    def output(self, text, color: QColor = None):
        color = color or QColor(0, 0, 0)
        self.ui.outputText.setTextColor(color)
        self.ui.outputText.insertPlainText(text + "\n")
        self.ui.outputText.moveCursor(QTextCursor.MoveOperation.End)

    @Slot()
    def on_btnTransform_clicked(self):
        with shelve.open("cache/cache.dump", writeback=True) as db:
            db["ncm_file_path"] = self.ui.ncmFilePath.text()
            db["out_file_path"] = self.ui.outFilePath.text()
            db["max_workers"] = self.ui.maxWorkers.value()

        if not self.ui.ncmFilePath.text():
            self.output("请选择ncm文件目录")
            return

        if not self.ui.outFilePath.text():
            self.output("请选择输出文件目录")
            return

        if not self.ui.maxWorkers.value():
            self.ui.maxWorkers.setValue(os.cpu_count())
            return

        self.ui.outputText.clear()
        self.obj.set_attr(
            self.ui.ncmFilePath.text(),
            self.ui.outFilePath.text(),
            self.ui.maxWorkers.value(),
        )
        self.qthread.start()


if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec())
